package com.cmcc.driver.data

import com.cmcc.driver.config.AppConfig
import com.cmcc.driver.data.entity.*
import com.cmcc.driver.data.entity.request.CarUpdateRequest
import com.cmcc.driver.data.entity.request.DeviceToken
import com.cmcc.driver.data.entity.request.MyLatLng
import com.cmcc.driver.data.entity.request.OrderReceiving
import com.cmcc.driver.data.entity.response.*
import com.cmcc.driver.data.service.ApiService
import com.cmcc.shared.SdkManager
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.model.DriverCache
import com.cmcc.shared.model.DriverInfo
import com.cmcc.shared.model.MsgBean
import com.cmcc.shared.network.RetrofitRequest
import com.cmcc.shared.network.interceptor.HttpLoggingInterceptor
import com.cmcc.shared.utils.TokenUtils
import com.google.android.gms.maps.model.LatLng
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import retrofit2.Response

class DriverRequest {

    private val driverApiService: ApiService = Network.getInstance().appApiService

    private fun getApiService(): ApiService {
        return RetrofitRequest.Builder().baseUrl(AppConfig.APP_DOMAIN)
            .setLogLevel(HttpLoggingInterceptor.Level.BODY)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept-Language", when (SdkManager.getLanguage()) {
                0 -> "en-US"
                1 -> "zh-CN"
                2 -> "zh-HK"
                else -> "zh-HK"
            })
            .addHeader(
                "Authorization",
//            "Bearer " + SpHelper.getParam(SdkManager.getApplicationContext()!!, SpKeys.USER_TOKEN, "")
                "Bearer " + TokenUtils.getUserToken()
            )
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
//        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .createService(ApiService::class.java)
    }

    /**
     * 获取附近的订单
     */
    suspend fun nearbyOrder(latLng: LatLng): Response<AppResponse<List<Order>>> {
        return getApiService().nearbyOrder(
            latLng.latitude.toString(), latLng.longitude.toString(), 100
        ).await()
    }


    /**
     * 同步firebase token 到服务器
     */
    suspend fun syncDeviceToken(token: String): Response<AppResponse<String>> {
        val deviceToken = DeviceToken(token)
        return getApiService().syncDeviceToken(deviceToken).await()
    }


    /**
     * 接单
     */
    suspend fun receivingOrder(orderId: String): Response<AppResponse<String>> {
        val orderReceiving = OrderReceiving(orderId)
        return getApiService().receivingOrder(orderReceiving).await()
    }

    suspend fun actionOrder(orderId: String): Response<AppResponse<String>> {
        val orderReceiving = OrderReceiving(orderId)
        return getApiService().actionOrder(orderReceiving).await()
    }

    suspend fun orderDetail(id: String): Response<AppResponse<OrderDetail>> {
        return getApiService().orderDetail(id).await()
    }

    suspend fun orderNumber(): Response<AppResponse<Double>> {
        return getApiService().orderNumber().await()
    }

    /**
     * 下一步
     */
    suspend fun nextOrder(
        orderId: String,
        payMethod: Int,
        mileageFee: Double,
        durationFee: Double,
        totalAmount: Double,
        status: Int
    ): Response<AppResponse<Int>> {
        var orderStatus =
            OrderStatus(orderId, payMethod, mileageFee, durationFee, totalAmount, status)
        return getApiService().nextOrder(orderStatus).await()
    }

    suspend fun refusalOrder(orderId: String): Response<AppResponse<Boolean>> {
        return getApiService().refusalOrder(orderId).await()
    }

    suspend fun cancel(orderId: String): Response<AppResponse<Boolean>> {
        val map = mapOf<String, String>("id" to orderId )
        return getApiService().cancel(map).await()
    }

//    /**
//     * 获取订单列表
//     * @param page 当前页
//     * @param pageSize 每页订单数
//     * @param role 用户角色 1：乘客，2司机
//     * @param status 所要查询的订单的状态，1是实时单，2是预约单，默认为1，可不填
//     */
//    suspend fun getOrderRecords(
//        page: Int,
//        pageSize: Int,
//        role: Int = 2,
//        status: Int? = null
//    ): Response<AppResponse<OrderRecord>> {
//        return getApiService().getOrderRecords(page, pageSize, role, status).await()
//    }

    /**
     * 获取订单列表
     * @param page 当前页
     * @param pageSize 每页订单数
     * @param role 用户角色 1：乘客，2司机
     * @param status 所要查询的订单的状态，1是实时单，2是预约单，默认为1，可不填
     */
    suspend fun getOrderRecords(
        page: Int,
        pageSize: Int,
        role: Int = 2,
        status: Int? = 5,
        statusOperator: String = ">"
    ): Response<AppResponse<OrderRecord>> {
        return getApiService().getOrderRecords(page, pageSize, role, status, statusOperator).await()
    }

    /**
     * 获取出单列表
     * @param page 当前页
     * @param pageSize 每页订单数
     * @param role 用户角色 1：乘客，2司机
     * @param status 所要查询的订单的状态，1是实时单，2是预约单，默认为1，可不填
     * @param statusOperator 后台操作符，固定值为“>”
     */
    suspend fun getOrderListInProgress(
        page: Int,
        pageSize: Int,
        role: Int = 2,
        status: Int = 6,
        statusOperator: String = "<"
    ): Response<AppResponse<OrderRecord>> {
        return getApiService().getOrderListInProgress(page, pageSize, role, status, statusOperator)
            .await()
    }

    /**
     * 查询正在进行的订单
     */
    suspend fun queryOrderInProgress(): Response<AppResponse<OrderDetail>> {
        return getApiService().queryOrderInProgress(2).await()
    }

    /**
     * 获取我的车辆信息
     *
     */
    suspend fun getCarInfo(): Response<AppResponse<List<CarInfo>>> {
        return getApiService().getCarInfo().await()
    }

    /**
     * 获取车辆类别列表
     */
    suspend fun getCarCategory(): Response<AppResponse<List<CarCategory>>> {
        return getApiService().getCarCategory().await()
    }


    /**
     * 更新司机定位
     * @param 当前坐标
     */
    suspend fun updateLocation(latLng: LatLng): Response<AppResponse<String>> {
        return getApiService().updateLocation(MyLatLng(latLng.latitude, latLng.longitude)).await()
    }

    /**
     * 获取司机缓存信息，其中包括头像、手机号等信息
     *
     * @param id 司机id
     *
     */
    suspend fun getDriverCache(id: String): Response<AppResponse<DriverCache>> {
        return getApiService().getDriverCache(id).await()
    }

    suspend fun getDriverInfo(): Response<AppResponse<DriverInfo>> {
        return getApiService().getDriverInfo().await()
    }

    /**
     * 更新车辆信息
     */
    suspend fun updateCarInfo(carInfo: CarUpdateRequest): Response<AppResponse<String>> {
        return getApiService().updateCarInfo(carInfo).await()
    }

    /**
     * 意见反馈
     * @param role 用户角色,1-司机,2-乘客
     * @param content 意见反馈内容
     */
    suspend fun feedback(feedback: Feedback): Response<AppResponse<String>> {
        return getApiService().feedback(feedback).await()
    }

    /**
     * 获取订单模板
     * @param id order template id
     */
    suspend fun getOrderTemplate(id: String): Response<AppResponse<OrderTemp>> {
        return getApiService().getOrderTemplate(id).await()
    }


    companion object {
        @Volatile
        private var instance: DriverRequest? = null

        fun getInstance(): DriverRequest {
            return instance ?: synchronized(this) {
                instance ?: DriverRequest().also { instance = it }
            }
        }
    }


    /**
     * 消息列表
     */
    suspend fun list( pageNum: Int, pageSize: Int): Response<AppResponse<MsgBean>> {
        return getApiService().list(pageNum,pageSize).await()
    }


}